package com.seg.system.service.impl;

import com.seg.common.exception.ServiceException;
import com.seg.common.utils.DateUtils;
import com.seg.common.utils.StringUtils;
import com.seg.common.utils.bean.BeanValidators;
import com.seg.system.domain.SelectData;
import com.seg.system.domain.TSparePart;
import com.seg.system.domain.TSparePartV;
import com.seg.system.mapper.TSparePartMapper;
import com.seg.system.service.ITSparePartService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Validator;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2023-06-15
 */
@Service
public class TSparePartServiceImpl implements ITSparePartService {
    @Autowired
    private TSparePartMapper tSparePartMapper;
    @Autowired
    protected Validator validator;
    private static final Logger log = LoggerFactory.getLogger(TSparePartServiceImpl.class);

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public TSparePart selectTSparePartById(Long id) {
        return tSparePartMapper.selectTSparePartById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param tSparePart 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<TSparePart> selectTSparePartList(TSparePart tSparePart) {
        return tSparePartMapper.selectTSparePartList(tSparePart);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param tSparePart 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertTSparePart(TSparePart tSparePart) {
        tSparePart.setCreateTime(DateUtils.getNowDate());
        int i = tSparePartMapper.selectTSparePartByCode(tSparePart.getMaterialNo());
        if (i == 1) {
            return -1;
        }
        return tSparePartMapper.insertTSparePart(tSparePart);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param tSparePart 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateTSparePart(TSparePart tSparePart) {
        tSparePart.setUpdateTime(DateUtils.getNowDate());
        return tSparePartMapper.updateTSparePart(tSparePart);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteTSparePartByIds(Long[] ids) {
        return tSparePartMapper.deleteTSparePartByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteTSparePartById(Long id) {
        return tSparePartMapper.deleteTSparePartById(id);
    }

    @Override
    public String importItemData(List<TSparePart> itemList, boolean updateSupport, String operName) {
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (TSparePart tSparePart : itemList) {
            try {
                int t = tSparePartMapper.selectTSparePartByCode(tSparePart.getMaterialNo());
                if (t == 0) {
                    BeanValidators.validateWithException(validator, tSparePart);
                    checkStockStatus(tSparePart);
                    checkDataFormat(tSparePart);
                    tSparePart.setCreateBy(operName);
                    tSparePart.setDelFlag("0");
                    tSparePartMapper.insertTSparePart(tSparePart);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、清单条目" + tSparePart.getMaterialNo() + " 导入成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、清单条目 " + tSparePart.getMaterialNo() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、清单条目 " + tSparePart.getMaterialNo() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public String importSapData(List<TSparePartV> itemList, boolean updateSupport, String operName) {
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        Date upDate = new Date();
        if (StringUtils.isNull(itemList) || itemList.size() == 0) {
            throw new ServiceException("导入清单数据不能为空！");
        }
        for (TSparePartV tSparePart : itemList) {
            try {
                BeanValidators.validateWithException(validator, tSparePart);
                TSparePart tp = new TSparePart();
                tp.setUpdateBy(operName);
                tp.setUpdateTime(upDate);
                tp.setUnitPrice(tSparePart.getUnitPrice());
                tp.setMaterialNo(tSparePart.getMaterialNo());
                tp.setSapStock(tSparePart.getSapStock());
                int ut = tSparePartMapper.updateTSparePartByMaterialNo(tp);
                if (ut == 1) {
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、清单条目" + tSparePart.getMaterialNo() + " 导入成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、清单条目 " + tSparePart.getMaterialNo() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、清单条目 " + tSparePart.getMaterialNo() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    private static void checkDataFormat(TSparePart tSparePart) {
        if (tSparePart.getStock() != null && tSparePart.getSapStock() != null && tSparePart.getSafetyStock() != null && tSparePart.getMaximalStock() != null) {
            if (tSparePart.getStock() < 0L || tSparePart.getSapStock() < 0L || tSparePart.getSafetyStock() < 0L || tSparePart.getMaximalStock() < 0L) {
                throw new ServiceException("存在小于0的整数");
            }
        }
        if (tSparePart.getUnitPrice() != null) {
            if (tSparePart.getUnitPrice().scale() > 2) {
                BigDecimal p = new BigDecimal(String.valueOf(tSparePart.getUnitPrice())).setScale(2, RoundingMode.HALF_UP);
                tSparePart.setUnitPrice(p);
            }
        }
    }

    private static void checkStockStatus(TSparePart tSparePart) {
        if (tSparePart.getSafetyStock() != null) {
            if (tSparePart.getStock() < tSparePart.getSafetyStock()) {
                tSparePart.setStatus1("CLS");
            }
        }
        if (tSparePart.getSapStock() != null) {
            if (tSparePart.getStock() < tSparePart.getSapStock()) {
                tSparePart.setStatus2("CLSAP");
            }
        }
    }

    @Override
    public List<SelectData> getMaterialType() {
        List<SelectData> list = new ArrayList<>();
        List<String> materialType = tSparePartMapper.tSparePartMapper();
        for (String s : materialType) {
            SelectData selectData = new SelectData();
            selectData.setName(s);
            selectData.setValue(s);
            list.add(selectData);
        }
        return list;
    }

    @Override
    public List<SelectData> getPartStatus1() {
        List<SelectData> list = new ArrayList<>();
        List<String> status1 = tSparePartMapper.getPartStatus1();
        for (String s : status1) {
            SelectData selectData = new SelectData();
            selectData.setName(s);
            selectData.setValue(s);
            list.add(selectData);
        }
        return list;
    }

    @Override
    public List<SelectData> getPartStatus2() {
        List<SelectData> list = new ArrayList<>();
        List<String> status2 = tSparePartMapper.getPartStatus2();
        for (String s : status2) {
            SelectData selectData = new SelectData();
            selectData.setName(s);
            selectData.setValue(s);
            list.add(selectData);
        }
        return list;
    }

    @Override
    public List<SelectData> getProductLine() {
        List<SelectData> list = new ArrayList<>();
        List<String> productLine = tSparePartMapper.getProductLine();
        for (String line : productLine) {
            SelectData selectData = new SelectData();
            selectData.setName(line);
            selectData.setValue(line);
            list.add(selectData);
        }
        return list;
    }

    @Override
    public List<SelectData> getStation(String line) {
        List<SelectData> list = new ArrayList<>();
        List<String> station = tSparePartMapper.getStation(line);
        for (String s : station) {
            SelectData selectData = new SelectData();
            selectData.setName(s);
            selectData.setValue(s);
            list.add(selectData);
        }
        return list;
    }

    @Override
    public TSparePart getPartById(Long id) {
        return tSparePartMapper.selectTSparePartById(id);
    }

    @Override
    public TSparePart getPartByMaterialNo(String materialNo) {
        return tSparePartMapper.getPartByMaterialNo(materialNo);

    }

    @Override
    public List<TSparePart> getPartByMaterialNos(Long[] materialNos) {
        return tSparePartMapper.getPartByMaterialNos(materialNos);
    }

    @Override
    public List<TSparePart> getPartByIds(Long[] ids) {
        return tSparePartMapper.getPartByIds(ids);
    }
}
